#include "scenic_jni_RenderCanvas.h"
#include "jawt_md.h"

#include <assert.h>

#include "common.h"
#include "jni_Debug.h"


using namespace Scenic::Renderer;


JNIEXPORT jint JNICALL Java_scenic_jni_RenderCanvas_createContext(
	JNIEnv* env, jobject canvas)
{
    JAWT awt;
    JAWT_DrawingSurface* ds;
    JAWT_DrawingSurfaceInfo* dsi;
    jboolean result;
    jint lock;
	jclass clazz = env->GetObjectClass(canvas);

    // Get the AWT
    awt.version = JAWT_VERSION_1_3;
    result = JAWT_GetAWT(env, &awt);
	assert(result != JNI_FALSE);

    // Get the drawing surface
    ds = awt.GetDrawingSurface(env, canvas);
    assert(ds != NULL);

    // Lock the drawing surface
    lock = ds->Lock(ds);
    assert((lock & JAWT_LOCK_ERROR) == 0);

    // Get the drawing surface info
    dsi = ds->GetDrawingSurfaceInfo(ds);

	Context *context = new Context();
	
	#ifdef DIRECTX
    // Get the platform-specific drawing info
    JAWT_Win32DrawingSurfaceInfo* dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo;
	context->hwnd = dsi_win->hwnd;
	printf("New Scenic canvas (HWND: %d, ContextId: %d)\n", dsi_win->hwnd, context->id);
	#endif
	#ifdef OPT_X11
	JAWT_X11DrawingSurfaceInfo *dsi_x = (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo;
	context->window = dsi_x->drawable;
	printf("New Scenic canvas (Window: %d, ContextId: %d)\n", dsi_x->drawable, context->id);
	#endif

	if(context->init() == false)
	{
		printf("Context initialization failed\n");
		delete context;
		ds->FreeDrawingSurfaceInfo(dsi);
		ds->Unlock(ds);
		awt.FreeDrawingSurface(ds);

		return 0;
	}

    //////////////////////////////
    // !!! DO PAINTING HERE !!! //
    //////////////////////////////

    // Free the drawing surface info
    ds->FreeDrawingSurfaceInfo(dsi);

    // Unlock the drawing surface
    ds->Unlock(ds);

    // Free the drawing surface
    awt.FreeDrawingSurface(ds);

	return context->id;
}

JNIEXPORT void JNICALL Java_scenic_jni_RenderCanvas_resetContext(
	JNIEnv* env, jobject canvas, jint contextId)
{
	ENTER(java_scenic_jni_RenderCanvas_resetContext);

	Context *context = getContext(contextId);

	context->reset();
}
